﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CuaHangMayTinh.BusinessEntities;
using CuaHangMayTinh.BusinessLogicLayer;
using CuaHangMayTinh.PresentationLayer.Report;
using CuaHangMayTinh.Utilities;
using DevComponents.DotNetBar.Controls;

namespace CuaHangMayTinh.PresentationLayer
{
    /// <summary>
    /// form trả hàng
    /// </summary>
    public partial class FormTraHang : Form
    {
        /// <summary>
        /// tạo đối tượng đổi sang chữ số
        /// </summary>
        private DoiSoSangChu doichuso = new DoiSoSangChu(1);

        /// <summary>
        /// giá trị khởi tạo
        /// </summary>
        public FormTraHang()
        {
            InitializeComponent();
        }

        /// <summary>
        /// giá trị khởi tạo có nhân viên
        /// </summary>
        /// <param name="entity"></param>
        public FormTraHang(NhanVienEntity entity):this()
        {
            NhanVien = entity;
        }

        /// <summary>
        /// nhân viên
        /// </summary>
        public NhanVienEntity NhanVien { get; set; }

        /// <summary>
        /// mã nhà cung cấp trả hàng
        /// </summary>
        private int maNCC = 0;

        /// <summary>
        /// lưu số luơng
        /// </summary>
        private int SoLuong = 0;

        /// <summary>
        /// lưu giá trị tổng tiền
        /// </summary>
        private decimal TongTien = 0; 

        public DataTable Table
        {
            get { return table; }
            set { table = value; }
        }

        /// <summary>
        /// tạo đỗi tượng nhà cung cấp
        /// </summary>
        private NhaCungCapEntity nhaCungCapEntity;

        /// <summary>
        /// tạo đối tượng xuất kho trả hàng
        /// </summary>
        private XuatKhoTraHangEntity xuatKhoTraHangEntity;

        /// <summary>
        /// danh sách model mặt hàng
        /// </summary>
        private List<ModelMatHangEntity> dsModelMatHangEntities = new List<ModelMatHangEntity>();

        /// <summary>
        /// danh sach chi tiết bán hàng entity
        /// </summary>
        private List<ChiTietXuatKhoTraHang> dsChiTietXuatKhoTraHangs = new List<ChiTietXuatKhoTraHang>();

        /// <summary>
        /// danh sách đơn vị tính
        /// </summary>
        private List<DonViTinhEntity> listDonViTinhEntities = DonViTinhManager.ConvertToList(DonViTinhManager.Find_All());


        /// <summary>
        /// bắt sự kiện laod của form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormTraHang_Load(object sender, EventArgs e)
        {
            LoadForm();
        }

        /// <summary>
        /// 
        /// </summary>
        void LoadForm()
        {
            xuatKhoTraHangEntity = new XuatKhoTraHangEntity();
            dsModelMatHangEntities = new List<ModelMatHangEntity>();
            LoadNhaCungCapToCbb();
            table = CreateDatable();
            dtime_ngaylap.Value = DateTime.Now;
            nhaCungCapEntity = new NhaCungCapEntity();
            Set_txtMaHD();
            btn_xoa.Enabled = true;
            btn_Them.Enabled = true;
            btn_thanhtoan.Enabled = true;
            dataGridViewX_Select.DataSource = new DataTable();
            label_soluong.Text = "0";
            label_tongtien.Text = "0";
            label_sotienchu.Text = "";
        }

        /// <summary>
        /// chứa thông tin của danh sách mặt hàng
        /// </summary>
        private DataTable dtmathang = MatHangManager.Find_All(false);

        /// <summary>
        /// load nhà cung cấp lên combobox
        /// </summary>
        private void LoadNhaCungCapToCbb()
        {
            DataTable dt = DataUtil.ChangeColumn(NhaCungCapManager.Find_All());
            cbb_nhacungcap.DataSource = dt;
            cbb_nhacungcap.DisplayMember = "Tên nhà cung cấp";
            cbb_nhacungcap.DropDownColumns = "Tên nhà cung cấp,Mã số thuế,Số điện thoại,Địa chỉ";
            cbb_nhacungcap.ValueMember = "Mã nhà cung cấp";
            cbb_nhacungcap.DropDownWidth = 400;
        }

        /// <summary>
        /// bắt sự kiện khi thay đổi cbb của nhà cung cấp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEx_nhacungcap_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbb_nhacungcap.Text = "...";
            ComboBoxEx ex = sender as ComboBoxEx;
            DataRowView row = (DataRowView)ex.SelectedItem;
            LoadMatHang();
            SetNhaCungCapEntity(row);
        }
        

        private void LoadMatHang()
        {
            DataRowView row = (DataRowView)cbb_nhacungcap.SelectedItem;
            DataTable dt = MatHangManager.Find_NhaCungCap((int)row[0]);
            if (dt == null)
            {
                cbb_mathang.DataSource = null;
                return;
            }
            nhaCungCapEntity = NhaCungCapManager.ConvertToList(NhaCungCapManager.Find_ID((int)row[0]))[0];
            dtmathang = dt;
            var dt2 = dt.AsEnumerable().Where(x => x.Field<int>("TinhTrang") != 4 && x.Field<int>("TinhTrang") != 1).CopyToDataTable();
            cbb_mathang.DataSource = dt2;
            cbb_mathang.ValueMember = "Serial_Code";
            cbb_mathang.Enabled = dt.Rows.Count > 0;
            btn_Them.Enabled = dt.Rows.Count > 0;
        }

        private void LoadMatHang(DataTable dt)
        {
            try
            {
                cbb_mathang.DataSource =
                dt.AsEnumerable().Where(x => x.Field<int>("TinhTrang") != 4).CopyToDataTable();
                cbb_mathang.ValueMember = "Serial_Code";
                cbb_mathang.Enabled = dt.Rows.Count > 0;
                btn_Them.Enabled = true;
            }
            catch (Exception)
            {
                cbb_mathang.Enabled = false;
                btn_Them.Enabled = false;
            }
        }

        /// <summary>
        /// lấy datarowview chuyển lên form
        /// </summary>
        /// <param name="row"></param>
        private void SetNhaCungCapEntity(DataRowView row)
        {
            txt_Ten.Text = row[1].ToString();
            txt_masothue.Text = row[2].ToString();
            txt_diachi.Text = row[3].ToString();
            txt_sodienthoai.Text = row[4].ToString();
        }

        /// <summary>
        /// tạo 1 datatable
        /// </summary>
        private DataTable table;

        /// <summary>
        /// tạo mới 1 datable có định kiểu
        /// </summary>
        /// <returns></returns>
        private DataTable CreateDatable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Serial");
            dt.Columns.Add("ModelMatHang");
            dt.Columns.Add("HangSX");
            dt.Columns.Add("NuocSX");
            dt.Columns.Add("BaoHanh");
            dt.Columns.Add("CauHinh");
            dt.Columns.Add("GiaNhap");
            dt.Columns.Add("LoaiMatHang");
            dt.Columns.Add("DonVitinh");
            return dt;
        }


        /// <summary>
        /// trộn 2 database với nhau
        /// </summary>
        /// <param name="dt1"></param>
        /// <returns></returns>
        private DataTable ADDtable(DataTable dt1)
        {
            DataTable dt2 = (DataTable) dataGridViewX_Select.DataSource;
            if (dt2 == null)
            {
                dt2 = table.Clone();
            }
            dt2.Merge(dt1);
            return dt2;
        }

//        /// <summary>
//        /// bắt sự kiện khi thay đổi model mặt hàng
//        /// </summary>
//        /// <param name="sender"></param>
//        /// <param name="e"></param>
//        private void comboBoxEx_modelmathang_SelectedIndexChanged(object sender, EventArgs e)
//        {
//            ModelMatHangEntity rowmodelmh = getModelMatHangEntity((DataRowView)comboBoxEx_modelmathang.SelectedValue);
//            int mamodel = rowmodelmh.MaModelMH;
//            var dr = dtmathang.AsEnumerable().Where(x => x.Field<int>("MaModelMH") == mamodel && x.Field<int>("TinhTrang") == 0);
//            DataTable table = new DataTable();
//            if (dr.Any())
//            {
//                comboBoxEx_mathang.Enabled = true;
//                table = dr.CopyToDataTable();
//                comboBoxEx_mathang.DataSource = table;
//                comboBoxEx_mathang.DisplayMember = "Serial_Code";
//                buttonX_Them.Enabled = true;
//            }
//            else
//            {
//                comboBoxEx_mathang.Enabled = false;
//                buttonX_Them.Enabled = false;
//            }
//        }

        private void buttonX_Them_Click(object sender, EventArgs e)
        {
            DataRowView rowView = (DataRowView)cbb_mathang.SelectedItem;
            DataTable dt = table.Clone();
            var row = MatHangManager.Find_Serial_Model((int)rowView[1],(string) cbb_mathang.SelectedValue, false);
            ///can than cho nay mai lay ham sau 
            if(row.Rows.Count>1)
                return;
            row.Rows[0][3] = 0;
            row.Rows[0][4] = 0;
            row.Rows[0][5] = 0;
            MatHangEntity matHangEntity = MatHangManager.ConvertToList(row)[0];
            ModelMatHangEntity modelMatHangEntity =
                ModelMatHangManager.ConvertToList(ModelMatHangManager.Find_ID(matHangEntity.MaModelMH, false))[0];
            ChiTietNhapHangEntity chiTietNhapHangEntity =
                ChiTietNhapHangManager.ConvertToList(ChiTietNhapHangManager.Find_MaHDNH(matHangEntity.MaHoaDonNhap))[0];
            dt.Rows.Add(new[]
            {
                cbb_mathang.SelectedValue,
                modelMatHangEntity.Model,
                modelMatHangEntity.HangSX,
                modelMatHangEntity.NuocSX,
                modelMatHangEntity.BaoHanh,
                modelMatHangEntity.CauHinh,
                chiTietNhapHangEntity.GiaNhap,
                modelMatHangEntity.MaLoaiMH,
                listDonViTinhEntities.AsEnumerable()
                    .Where(x => x.MaDonViTinh == modelMatHangEntity.MaDonViTinh)
                    .Select(x => x.DonVi)
                    .FirstOrDefault()
            });
            var t = dtmathang.AsEnumerable().FirstOrDefault(x => x.Field<int>("MaMH") == matHangEntity.MaMH);
            t["TinhTrang"] = 4;
            if (dsModelMatHangEntities.Any(x => x.MaModelMH == modelMatHangEntity.MaModelMH))
            {
                dsModelMatHangEntities.FirstOrDefault(x => x.MaModelMH == modelMatHangEntity.MaModelMH).ListMatHang.Add(matHangEntity);
                dsChiTietXuatKhoTraHangs.FirstOrDefault(x => x.MaModelMH == modelMatHangEntity.MaModelMH).SoLuong++;
            }
            else
            {
//                dsModelMatHangEntities.Add(rowmodelmh);
//                var chitietbanhang = new ChiTietBanHangEntity(0, rowmodelmh.MaModelMH, 1, gia);
//                dscChiTietBanHangEntities.Add(chitietbanhang);
                modelMatHangEntity.ListMatHang.Add(matHangEntity);
                dsModelMatHangEntities.Add(modelMatHangEntity);
                dsChiTietXuatKhoTraHangs.Add(new ChiTietXuatKhoTraHang(0, modelMatHangEntity.MaModelMH, 1, chiTietNhapHangEntity.GiaNhap, txt_ghichu.Text));
            }
            
            SoLuong += 1;
            label_soluong.Text = SoLuong.ToString();
            TongTien += chiTietNhapHangEntity.GiaNhap;
            label_tongtien.Text = TongTien + " Đồng";
            doichuso.So = Convert.ToInt32(TongTien);
            label_sotienchu.Text = doichuso.ToString();
            dataGridViewX_Select.DataSource = ADDtable(dt);
            
            
            LoadMatHang(dtmathang);
            if (dataGridViewX_Select.Rows.Count > 0)
                cbb_nhacungcap.Enabled = false;
            else
                cbb_nhacungcap.Enabled = true;
        }

        /// <summary>
        /// lấy modelmat hang từ datagirview row
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private ModelMatHangEntity getModelMatHangEntity(DataRowView row)
        {
            var entity = new ModelMatHangEntity()
            {
                MaModelMH = (int)row[0],
                MaLoaiMH = (int)row[1],
                Model = (string)row[2],
                HangSX = (string)row[3],
                NuocSX = (string)row[4],
                CauHinh = (string)row[5],
                BaoHanh = (int)row[6],
                SoLuong = (int)row[7],
                TinhTrang = (int)row[8],
                MaDonViTinh = (int)row[9]
            };
            return entity;
        }

        /// <summary>
        /// lấy mặt hàng entity từ datarowview 
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private MatHangEntity getMatHangEntity(DataRowView row)
        {
            MatHangEntity entity = new MatHangEntity()
            {
                MaMH = (int)row[0],
                MaModelMH = (int)row[1],
                MaHoaDonNhap = (int)row[2],
                MaHoaDonBan = 0,
                MaPhieuXuatKhoTraHang = 0,
                Serial_Code = (string)row[6],
                MaPhieuBaoHanhSuaChua = 0,
                TinhTrang = 0
            };
            return entity;
        }

        private void buttonX_thanhtoan_Click(object sender, EventArgs e)
        {
            if (dataGridViewX_Select.Rows.Count > 0)
            {
                XuatKhoTraHangEntity entity = new XuatKhoTraHangEntity(txt_maphieunhap.Text, NhanVien.MaNV,
                    (int) cbb_nhacungcap.SelectedValue, dtime_ngaylap.Value, TongTien, txt_ghichu.Text);
                entity.ListChiTiet = dsChiTietXuatKhoTraHangs;
                entity.ListModel = dsModelMatHangEntities;
                if (XuatKhoTraHangManager.Insert(entity) > 0)
                {
                    MessageBox.Show("Trả hàng thành công !");
                    btn_thanhtoan.Enabled = false;
                    btn_IN.Enabled = true;
                    toolStripbtn_Excel.Enabled = true;
                    toolStripBtn_In.Enabled = true;
                    btn_xoa.Enabled = false;
                    btn_Them.Enabled = false;
                    xuatKhoTraHangEntity = entity;
                }
                else
                {
                    MessageBox.Show("Lỗi trả hàng !");
                }
            }
            else
            {
                MessageBox.Show("Chưa có sản phẩm cần trả");
            }
        }

        private void buttonX_xoa_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow selectrow in dataGridViewX_Select.SelectedRows)
            {
                var serial = selectrow.Cells[0].Value;
                foreach (var mathangentity in dsModelMatHangEntities)
                {
                    SoLuong -= mathangentity.ListMatHang.Where(x => x.Serial_Code == (string)serial).Count();
                    var t = dtmathang.AsEnumerable().FirstOrDefault(x => x.Field<string>("Serial_code") == serial);
                    t["TinhTrang"] = 0;
                    if (mathangentity.ListMatHang.Any(x => x.Serial_Code == (string) serial))
                    {
                        dataGridViewX_Select.Rows.Remove(dataGridViewX_Select.SelectedRows[0]);
                        mathangentity.ListMatHang.RemoveAll(x => x.Serial_Code == (string)serial);
                        decimal gia =
                            dsChiTietXuatKhoTraHangs.FirstOrDefault(x => x.MaModelMH == mathangentity.MaModelMH).Gia;
                        TongTien -= gia;
                        if (mathangentity.ListMatHang.Count < 1)
                            dsChiTietXuatKhoTraHangs.RemoveAll(x => x.MaModelMH == mathangentity.MaModelMH);
                    }
                }
            }
            dsModelMatHangEntities.RemoveAll(x => x.ListMatHang.Count == 0);
            label_soluong.Text = SoLuong.ToString();
            label_tongtien.Text = TongTien + " Đồng";
            doichuso.So = Convert.ToInt32(TongTien);
            label_sotienchu.Text = doichuso.ToString();
            LoadMatHang(dtmathang);
            if (dataGridViewX_Select.Rows.Count == 0)
                cbb_nhacungcap.Enabled = true;
        }

        private void toolStripbtn_Excel_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Excel 2007 Files|*.xlsx";
            if (save.ShowDialog() == DialogResult.OK)
            {

                Byte[] bytes = ExcelLibrary.ExportExcel((DataTable) dataGridViewX_Select.DataSource, "Trả hàng",save.FileName);
                string filePath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Application.StartupPath)),
                    save.FileName);
                File.WriteAllBytes(filePath, bytes);
                if (MessageBox.Show("Bạn có muốn mở files lên không!", "Thông báo !", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    ProcessStartInfo pi = new ProcessStartInfo(filePath);
                    Process.Start(pi);
                }
            }
        }

        private void btn_IN_Click(object sender, EventArgs e)
        {
            var form = (FormChinh)this.MdiParent;
            FormReportHoaDon reportHoaDon = new FormReportHoaDon(xuatKhoTraHangEntity, form.NhanVien,nhaCungCapEntity, listDonViTinhEntities, true);
            reportHoaDon.ShowDialog();
        }

        private void button_xemtruoc_Click(object sender, EventArgs e)
        {
            if (dataGridViewX_Select.Rows.Count > 0)
            {
                var form = (FormChinh) this.MdiParent;
                xuatKhoTraHangEntity.ListChiTiet = dsChiTietXuatKhoTraHangs;
                xuatKhoTraHangEntity.ListModel = dsModelMatHangEntities;
                FormReportHoaDon reportHoaDon = new FormReportHoaDon(xuatKhoTraHangEntity, form.NhanVien,
                    nhaCungCapEntity, listDonViTinhEntities, false);
                reportHoaDon.ShowDialog();
            }
        }

        void Set_txtMaHD()
        {
            DataTable dt;
            txt_maphieunhap.Enabled = false;
            dt = BanHangManager.GetMaHDMax();
            string nam = DateTime.Now.Year.ToString().Substring(1, DateTime.Now.Year.ToString().Length - 1);
            if (dt.Rows.Count == 0)
            {
                txt_maphieunhap.Text = nam + "-0000001";
                return;
            }
            string mahd = dt.Rows[0][0].ToString();
            string[] temp = mahd.Split('-');
            if (temp[0].CompareTo(nam) != 0)
            {
                txt_maphieunhap.Text = nam + "-0000001";
                return;
            }
            int duoi = 0;
            string Duoi = "";
            if (temp[0].CompareTo(nam) == 0)
            {
                mahd = "";
                duoi = (int.Parse(temp[1]) + 1);
                if (duoi < 10)
                    Duoi = "-000000" + duoi;
                else
                    if (duoi < 100)
                        Duoi = "-00000" + duoi;
                    else
                        if (duoi < 1000)
                            Duoi = "-0000" + duoi;
                        else
                            if (duoi < 10000)
                                Duoi = "-000" + duoi;
                            else
                                if (duoi < 100000)
                                    Duoi = "-00" + duoi;
                mahd = temp[0] + Duoi;
                txt_maphieunhap.Text = mahd;
            }
        }

        private void toolStripBtn_TaoMoi_Click(object sender, EventArgs e)
        {
            LoadForm();
        }

    }
}
